package com.rlz.framemm.algorithm

import java.lang.RuntimeException
import java.util.*

/**
 * Created by RLZ
 * on 2021/9/10
 *
 */
class MinStack<T : Comparable<T>> {

    private var mDataStack: Stack<T> = Stack()
    private var mMinStack: Stack<T> = Stack()

    fun push(newValue: T) {
        when {
            mMinStack.isEmpty() -> mMinStack.push(newValue)
            newValue < getMin() -> mMinStack.push(newValue)
            else -> mMinStack.push(mMinStack.peek())
        }
        mDataStack.push(newValue)
    }

    private fun getMin(): T {
        if (mMinStack.isEmpty()) toThrow()
        return mMinStack.peek()
    }

    fun pop(): T {
        if (mDataStack.isEmpty()) toThrow()
        mMinStack.pop()
        return mDataStack.pop()
    }

    fun peek(): T {
        if (mDataStack.isEmpty()) toThrow()
        return mDataStack.peek()
    }

    private fun toThrow() {
        throw RuntimeException("容器是个空的")
    }

    fun size(): Int {
        return mDataStack.size
    }
}